package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ulorder.Ulorder;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.rest.qimen.qmentity.request.stockout.StockOutItem;
import com.topisv.tms.rest.qimen.qmentity.request.stockout.StockOutRequest;
import com.topisv.tms.rest.qimen.qmentity.response.QMReponse;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.qmentity.response.deliveryorder.DeliveryorderResponse;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.rest.qimen.util.delivery.TransferHelper;
import com.topisv.tms.rest.qimen.util.validator.ValidatorUtil;
import com.topisv.tms.service.ulorder.UlorderService;

/**
 * 出库单创建处理类
 *  @author chenhongtao
 */
@Component
@Lazy(false)
public class StockoutCreateService{
	
	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private UlorderService ulorderService;
	
	private static final Logger logger = LoggerFactory.getLogger(StockoutCreateService.class);

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public ResponseParams execute(RequestParams params) {
		// TODO Auto-generated method stub
		ResponseParams response = new ResponseParams();
		DeliveryorderResponse deliveryorderResponse = new DeliveryorderResponse();
		Ulorder ulorder = null;
		try {
			logger.info("新增出库");
			String stringXml = params.getRequestXml();
			StockOutRequest stockOutRequest = JAXB.unmarshal(new StringReader(stringXml), StockOutRequest.class);
			
	        // 报文校验
	        String reqValidatorMsg = ValidatorUtil.qmXmlValidator(stockOutRequest);
	        if (!ValidatorUtil.SUCCESS_CODE.equals(reqValidatorMsg)) {
	            response.setResponseXml(reqValidatorMsg.toString());
	            return response;
	        }
			
			Map<String, EdiGoodsSku> skuMap = new HashMap<String, EdiGoodsSku>();
			fillCache(stockOutRequest,skuMap);
			EdiOrder ediOrder = TransferHelper.stockOuttoEdiOrder(stockOutRequest, skuMap);
			ulorder = ulorderService.getCustomerOrder(ediOrder.getCustomerCode(), ediOrder.getCustomerOrdeno());
			
			if (null != ulorder && !StringUtils.equals(ulorder.getStatus(),"cancel")) {
				deliveryorderResponse.setFlag("failure");
				deliveryorderResponse.setCode(QMErrorCode.SKU_EXISTS.getCode());
				deliveryorderResponse.setMessage("订单已存在");
				deliveryorderResponse.setDeliveryOrderId(ulorder.getOrderno());
				deliveryorderResponse.setCreateTime(ulorder.getCreateTime());
				response = returnResponseParams(deliveryorderResponse);
				return response;
			}
			ulorderService.createBill_2(ediOrder);
			deliveryorderResponse.setFlag("success");
			deliveryorderResponse.setCode(QMErrorCode.SUCCESS.getCode());
			deliveryorderResponse.setMessage(QMErrorCode.SUCCESS.getMessage());
			deliveryorderResponse.setDeliveryOrderId(ediOrder.getOrdeno());
			deliveryorderResponse.setCreateTime(new Date());

		}catch (Exception e) {
			logger.info("保存错误",e);
			deliveryorderResponse.setFlag("failure");
			deliveryorderResponse.setCode("QMINFO001");
			deliveryorderResponse.setMessage("失败：" + e.getMessage());
			deliveryorderResponse.setDeliveryOrderId("");
		}
		response = returnResponseParams(deliveryorderResponse);
		return response;
	}
	private void fillCache(StockOutRequest stockOutRequest, Map<String, EdiGoodsSku> skuMap) {
		List<StockOutItem> items = stockOutRequest.getStockOutItems();
		for (StockOutItem stockOutItem : items) {
			EdiGoodsSku ediGoodsSku = skuMap.get(stockOutItem.getItemCode());
			if (ediGoodsSku == null) {
			    EdiGoodsSku goodsSku = ediGoodsSkuDao.findOne(Long.valueOf(stockOutItem.getItemId()));
				if (goodsSku == null) {
                    throw new RuntimeException("itemID有误");
                }
				skuMap.put(stockOutItem.getItemCode(), goodsSku);
			}
		}
	}
	
	/**
	 * 
	 * 出库订单创建接口返回报文
	 * 
	 * @param deliveryorderResponse
	 * @return
	 */
	public ResponseParams returnResponseParams(DeliveryorderResponse deliveryorderResponse) {
		ResponseParams response = new ResponseParams();
		StringWriter writer = new StringWriter();
		JAXB.marshal(deliveryorderResponse,writer);
		response.setResponseXml(writer.toString());
		return response;
	}
}
